<!-- 用户管理组件 -->
<template>
    <div id="user_container">
        <div class="header-actions">
            <div>
                <!-- 左侧标题 -->
                <h2>用户管理</h2>
            </div>
            <div>
                <el-button type="primary" @click="openDialog()">新增用户</el-button>
                <el-input v-model="searchKeyword" placeholder="搜索用户邮箱" style="width: 300px; margin-left: 16px" clearable
                    @clear="fetchUserList" @keyup.enter="fetchUserList">
                    <template #append>
                        <el-button :icon="Search" @click="fetchUserList" />
                    </template>
                </el-input>
            </div>
        </div>

        <!-- 用户表格 -->
        <el-table :data="userList" stripe style="width: 100%; margin-top: 20px" v-loading="loading">
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="user_name" label="用户名" width="150" />
            <el-table-column prop="email" label="邮箱" />
            <el-table-column prop="user_id" label="用户ID" />
            <el-table-column prop="create_time" label="创建时间" width="180" />
            <el-table-column prop="admin" label="角色" width="100">
                <template #default="scope">
                    <el-tag :type="scope.row.admin === 1 ? 'danger' : 'info'">
                        {{ scope.row.admin === 1 ? '管理员' : '普通用户' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
                <template #default="scope">
                    <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                        {{ scope.row.status === 1 ? '启用' : '禁用' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
                <template #default="scope">
                    <el-button size="small" type="primary" @click="openDialog(scope.row)">
                        编辑
                    </el-button>
                    <el-button size="small" :type="scope.row.status === 1 ? 'danger' : 'success'"
                        @click="changeUserStatus(scope.row)">
                        {{ scope.row.status === 1 ? '禁用' : '启用' }}
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="totalUsers"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>

        <!-- 用户表单对话框 -->
        <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑用户' : '新增用户'" width="500px" destroy-on-close>
            <el-form ref="userFormRef" :model="userForm" :rules="userFormRules" label-width="100px"
                label-position="right">
                <el-form-item label="用户ID" prop="user_id" >
                    <el-input v-model="userForm.user_id" placeholder="请输入用户ID" :disabled="isEdit"/>
                </el-form-item>
                <el-form-item label="用户名" prop="user_name">
                    <el-input v-model="userForm.user_name" placeholder="请输入用户名" />
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="userForm.email" placeholder="请输入邮箱" />
                </el-form-item>
                <el-form-item label="密码" prop="password" v-if="!isEdit">
                    <el-input v-model="userForm.password" type="password" placeholder="请输入密码" show-password />
                </el-form-item>
                <el-form-item label="密码" prop="password" v-else>
                    <el-input v-model="userForm.password" type="password" placeholder="留空则不修改密码" show-password />
                </el-form-item>
                <el-form-item label="是否管理员" prop="admin">
                    <el-switch v-model="userForm.admin" :active-value="1" :inactive-value="0" active-text="是"
                        inactive-text="否" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm" :loading="submitLoading">
                        确认
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import axios from "../../public/request"

// 数据定义
const userList = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const submitLoading = ref(false)
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const totalUsers = ref(0)
const userFormRef = ref(null)

// 表单数据
const userForm = reactive({
    user_id: '',
    user_name: '',
    email: '',
    password: '',
    admin: 0
})

// 表单验证规则
const userFormRules = {
    user_id: [
        { required: true, message: '请输入用户ID', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
    ],
    user_name: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
    ],
    password: [
        { min: 6, message: '密码不能少于 6 个字符', trigger: 'blur' }
    ]
}

// 生命周期钩子
onMounted(() => {
    fetchUserList()
})

// 获取用户列表
const fetchUserList = () => {
    loading.value = true
    axios.post('/user_manage/users', {
        page: currentPage.value,
        size: pageSize.value,
        email: searchKeyword.value
    })
        .then(response => {
            if (response.data.code === 1) {
                userList.value = response.data.data.records
                totalUsers.value = response.data.data.total
            } else {
                ElMessage.error(response.data.msg || '获取用户列表失败')
            }
        })
        .catch(error => {
            console.error('获取用户列表出错:', error)
            ElMessage.error('获取用户列表失败')
        })
        .finally(() => {
            loading.value = false
        })
}

// 打开用户表单对话框
const openDialog = (row = null) => {
    resetForm()
    if (row) {
        isEdit.value = true
        Object.keys(userForm).forEach(key => {
            if (key in row) {
                userForm[key] = row[key]
            }
        })
        userForm.password = '' // 编辑模式下密码置空
    } else {
        isEdit.value = false
    }
    dialogVisible.value = true
}

// 重置表单
const resetForm = () => {
    if (userFormRef.value) {
        userFormRef.value.resetFields()
    }
    Object.keys(userForm).forEach(key => {
        userForm[key] = key === 'admin' ? 0 : ''
    })
}

// 提交表单
const submitForm = () => {
    userFormRef.value.validate(valid => {
        if (!valid) return

        submitLoading.value = true

        if (isEdit.value) {
            // 更新用户
            axios.put(`/user_manage/users/${userForm.user_id}`, userForm)
                .then(response => {
                    if (response.data.code === 1) {
                        ElMessage.success(response.data.msg || '用户更新成功')
                        dialogVisible.value = false
                        fetchUserList()
                    } else {
                        ElMessage.error(response.data.msg || '用户更新失败')
                    }
                })
                .catch(error => {
                    console.error('更新用户出错:', error)
                    ElMessage.error('用户更新失败')
                })
                .finally(() => {
                    submitLoading.value = false
                })
        } else {
            // 新增用户
            axios.post('/user_manage/addUsers', userForm)
                .then(response => {
                    if (response.data.code === 1) {
                        ElMessage.success(response.data.msg || '用户添加成功')
                        dialogVisible.value = false
                        fetchUserList()
                    } else {
                        ElMessage.error(response.data.msg || '用户添加失败')
                    }
                })
                .catch(error => {
                    console.error('添加用户出错:', error)
                    ElMessage.error('用户添加失败')
                })
                .finally(() => {
                    submitLoading.value = false
                })
        }
    })
}

// 更改用户状态
const changeUserStatus = (row) => {
    const newStatus = row.status === 1 ? 0 : 1
    const statusText = newStatus === 1 ? '启用' : '禁用'

    ElMessageBox.confirm(
        `确定要${statusText}用户 "${row.user_name}" 吗？`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    )
        .then(() => {
            axios.put(`/user_manage/opsUsers/${row.user_id}/status/${newStatus}`)
                .then(response => {
                    if (response.data.code === 1) {
                        ElMessage.success(response.data.msg || `用户${statusText}成功`)
                        fetchUserList()
                    } else {
                        ElMessage.error(response.data.msg || `用户${statusText}失败`)
                    }
                })
                .catch(error => {
                    console.error(`${statusText}用户出错:`, error)
                    ElMessage.error(`用户${statusText}失败`)
                })
        })
        .catch(() => {
            // 取消操作
        })
}

// 分页处理
const handleSizeChange = (val) => {
    pageSize.value = val
    fetchUserList()
}

const handleCurrentChange = (val) => {
    currentPage.value = val
    fetchUserList()
}
</script>

<style scoped>
#user_container {
    padding: 20px;
}

.header-actions {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20px;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}

.el-tag {
    margin-right: 5px;
}
</style>